<!-- 我的申报 -->
<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :model="searchInfo" :inline="true" size="small">
        <el-form-item label="项目名称">
          <el-input v-model="searchInfo.name" placeholder="请输入项目名称" clearable />
        </el-form-item>
        <el-form-item label="项目分类">
          <el-select v-model="searchInfo.projectClass" clearable placeholder="请选择">
            <el-option v-for="item in projectClassList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="流转状态">
          <el-select v-model="searchInfo.status" clearable placeholder="请选择">
            <el-option v-for="item in circulationStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="申报时间">
          <el-date-picker
            v-model="timeValue"
            style="width: 300px;"
            clearable
            size="small"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            align="right"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="onSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          <el-button icon="el-icon-bell" size="small" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="ticketList" stripe>
        <el-table-column label="#" type="index" width="80" align="center" />
        <el-table-column label="项目名称" prop="name" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="项目编号" prop="projectNo" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="项目分类" :show-overflow-tooltip="true" prop="projectClassName" align="center" width="120" />
        <el-table-column label="申请科室" :show-overflow-tooltip="true" prop="applyDeptId" align="center" width="120" />
        <el-table-column label="技术分类" :show-overflow-tooltip="true" prop="techTypeNames" align="center" width="120" />
        <el-table-column label="项目负责人" align="center" prop="applyManagerName" width="180" />
        <el-table-column label="负责人联系方式" align="center" prop="projectManagerContact" width="180" />
        <el-table-column label="目标例数" align="center" prop="targetNumber" width="180" />
        <el-table-column label="项目成员" align="center" prop="projectMemberNames" width="180" />
        <el-table-column label="填报人" align="center" prop="applyUserName" width="180" />
        <el-table-column label="填报人工号" align="center" prop="workNumber" width="180" />
        <el-table-column label="填报时间" align="center" prop="createTime" width="180" />
        <!-- <el-table-column label="流转状态" prop="statusName" :show-overflow-tooltip="true" width="150" align="center" />
        <el-table-column label="提交状态" prop="auditStatusName" :show-overflow-tooltip="true" width="120" align="center" /> -->

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
          <template slot-scope="scope">
            <el-button v-if="scope.row.auditStatus === 1 || scope.row.auditStatus === 4" v-permisaction="['edit:MyApplyProject']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.auditStatus === 2 || scope.row.auditStatus === 3" v-permisaction="['detail:MyApplyProject']" size="mini" type="text" icon="el-icon-document" @click="handleView(scope.row)">表单数据</el-button>
            <el-button v-permisaction="['history:MyApplyProject']" size="mini" type="text" icon="el-icon-time" @click="handleHistoryView(scope.row)">审批历史</el-button>
            <el-button v-if="scope.row.auditStatus === 1" v-permisaction="['delete:MyApplyProject']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pageInfo.total > 0" :total="pageInfo.total" :page.sync="pageInfo.currentPage" :limit.sync="pageInfo.pageSize" @pagination="onPagination" />
    </el-card>
    <ReviewDialog ref="reviewDialog" @refreshTable="getList" />
    <EditDialog ref="editDialog" @refreshTable="getList" />
    <HistoryDialog ref="historyDialog" source="apply" />
  </div>
</template>

<script>
import {
  reopenWorkOrder,
  doDelete,
  doMyTechQuery
} from '@/api/xjs/work-order'
import { mapGetters } from 'vuex'
// 搜索
import ReviewDialog from './components/review'
import HistoryDialog from '../components/history'
import EditDialog from './components/editDialog'
import { parseTime } from '@/utils'
import { projectClassList, auditStatusList } from '@/utils/common'
import { newListUser } from '@/api/system/sysuser'
import * as XLSX from 'xlsx'

export default {
  name: 'MyApply',
  components: { ReviewDialog, HistoryDialog, EditDialog },
  computed: {
    ...mapGetters(['circulationStatus'])
  },
  data() {
    return {
      searchInfo: {
        name: '', // 项目名称
        projectClass: null, // 项目分类
        status: null, // 流转状态
        startCreateTime: null, // 申报开始时间
        endCreateTime: null // 申报结束时间
      },
      searchInfoCopy: null, // 用于重置
      pageInfo: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      projectClassList: projectClassList, // 项目分类列表
      auditStatusList: auditStatusList, // 提交状态
      parseTime: parseTime, // 时间处理
      timeValue: [],
      loading: false, // loading加载
      ticketList: [], // 列表数据
      allUsers: [], // 所有用户列表
      techTypeMap: {
        11: '一级项目（国内医院尚未开展的技术项目）',
        12: '二级项目（本学科近年来发展成熟的、在国内已有医院开展、省内及本院尚未开展）',
        13: '三级项目（本学科发展成熟，在国内及省内均有开展，而本院尚未开展）',
        14: '四级项目（报备类项目，创新性一般，技术含量不高，仅为设备、试剂、耗材等引进或调整，在本院尚未开展的技术项目）',
        21: '一级项目（国内医院尚未开展的技术项目）',
        22: '二级项目（本学科近年来发展成熟的、在国内已有医院开展、省内及本院尚未开展）',
        23: '三级项目（本学科发展成熟，在国内及省内均有开展，而本院尚未开展）',
        24: '四级项目（报备类项目，创新性一般，技术含量不高，仅为设备、试剂、耗材等引进或调整，在本院尚未开展的技术项目）'
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      // 导出表头配置
      exportColumns: [
        { label: '项目名称', prop: 'name' },
        { label: '项目编号', prop: 'projectNo' },
        { label: '项目分类', prop: 'projectClassName' },
        { label: '申请科室', prop: 'applyDeptId' },
        { label: '技术分类', prop: 'techTypeNames' },
        { label: '项目负责人', prop: 'applyManagerName' },
        { label: '负责人联系方式', prop: 'projectManagerContact' },
        { label: '目标例数', prop: 'targetNumber' },
        { label: '项目成员', prop: 'projectMemberNames' },
        { label: '填报人', prop: 'applyUserName' },
        { label: '填报人工号', prop: 'workNumber' },
        { label: '填报时间', prop: 'createTime' }
      ]
    }
  },
  watch: {
    // 处理申报时间
    timeValue: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length) {
          this.searchInfo.startCreateTime = newVal[0]
          this.searchInfo.endCreateTime = newVal[1]
        } else {
          this.searchInfo.startCreateTime = null
          this.searchInfo.endCreateTime = null
        }
      },
      deep: true
    }
  },
  created() {
    this.searchInfoCopy = JSON.parse(JSON.stringify(this.searchInfo))
    this.getList()
  },
  methods: {
    goUrl(key) {
      this.$router.push({ path: '/xjsxxm/' + key })
    },
    // 搜索
    onSearch() {
      this.pageInfo.currentPage = 1
      this.getList()
    },
    // 重置
    resetQuery() {
      this.timeValue = []
      this.searchInfo = JSON.parse(JSON.stringify(this.searchInfoCopy))
      this.getList()
    },
    // 分页
    onPagination(obj) {
      this.pageInfo.currentPage = obj.page
      this.pageInfo.pageSize = obj.limit
      this.getList()
    },
    // 列表数据
    getList() {
      const params = {
        ...this.searchInfo,
        ...this.pageInfo
      }
      // 先获取用户列表
      newListUser({
        currentPage: 1,
        pageSize: 10000,
        empNo: null,
        deptID: "",
        userID: "",
        userName: ""
      }).then(userRes => {
        if (userRes.records) {
          this.allUsers = userRes.records.filter(user => 
            user.vldFG === '0' && user.name && user.empNo
          )
        }
        
        // 然后获取项目列表
        doMyTechQuery(params).then(res => {
          const data = res.records
          data.forEach(item => {
            const projectObj = this.projectClassList.find(it => it.value === item.projectClass)
            const statusObj = this.circulationStatus && this.circulationStatus.find(it => it.value === item.status)
            const auditStatusObj = this.auditStatusList.find(it => it.value === item.auditStatus)
            
            // 处理项目分类
            item.projectClassName = projectObj ? projectObj.label : ''
            item.statusName = statusObj ? statusObj.label : ''
            item.auditStatusName = auditStatusObj ? auditStatusObj.label : ''
            
            // 处理技术分类
            if (item.techType) {
              const techTypes = item.techType.split(',').map(Number)
              item.techTypeNames = techTypes.map(type => this.techTypeMap[type] || '').filter(Boolean).join('、')
            }
            
            // 处理项目成员
            if (item.projectMember) {
              const memberIds = item.projectMember.split(',').filter(Boolean)
              const memberNames = memberIds.map(id => {
                const user = this.allUsers.find(u => u.id === Number(id) || u.id === id)
                return user ? user.name : ''
              }).filter(Boolean)
              item.projectMemberNames = memberNames.join('、')
            }
          })
          this.ticketList = data
          this.pageInfo.total = res.total
        })
      })
    },
    // 表单数据弹窗
    handleView(row) {
      // this.$refs.reviewDialog.open(row.process, row.id)
      // this.$refs.reviewDialog.getNewDeptTreeList()
      // this.$refs.reviewDialog.getNewDeptListManager()
      this.$refs.reviewDialog.open(row)
    },
    // 重新编辑提交弹窗
    handleEdit(row) {
      // this.$refs.editDialog.getNewDeptTreeList()
      // this.$refs.editDialog.getNewDeptListManager()
      this.$refs.editDialog.open(row)
    },
    // 查看进度和审批历史弹窗
    handleHistoryView(row) {
      this.$refs.historyDialog.open(row)
    },
    handleReopen(id) {
      this.$confirm('根据此工单新建一个新的工单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        reopenWorkOrder(id).then(res => {
          this.getList()
          this.$message({
            type: 'success',
            message: '成功!'
          })
        })
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          doDelete({ id: row.id }).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 导出数据
    handleExport() {
      this.$confirm('确认要导出所有数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        // 获取所有数据
        const params = {
          ...this.searchInfo,
          currentPage: 1,
          pageSize: 999999 // 获取所有数据
        }
        
        // 先获取用户列表
        newListUser({
          currentPage: 1,
          pageSize: 10000,
          empNo: null,
          deptID: "",
          userID: "",
          userName: ""
        }).then(userRes => {
          if (userRes.records) {
            this.allUsers = userRes.records.filter(user => 
              user.vldFG === '0' && user.name && user.empNo
            )
          }
          
          // 然后获取项目列表
          doMyTechQuery(params).then(res => {
            const data = res.records
            data.forEach(item => {
              const projectObj = this.projectClassList.find(it => it.value === item.projectClass)
              const statusObj = this.circulationStatus && this.circulationStatus.find(it => it.value === item.status)
              const auditStatusObj = this.auditStatusList.find(it => it.value === item.auditStatus)
              
              // 处理项目分类
              item.projectClassName = projectObj ? projectObj.label : ''
              item.statusName = statusObj ? statusObj.label : ''
              item.auditStatusName = auditStatusObj ? auditStatusObj.label : ''
              
              // 处理技术分类
              if (item.techType) {
                const techTypes = item.techType.split(',').map(Number)
                item.techTypeNames = techTypes.map(type => this.techTypeMap[type] || '').filter(Boolean).join('、')
              }
              
              // 处理项目成员
              if (item.projectMember) {
                const memberIds = item.projectMember.split(',').filter(Boolean)
                const memberNames = memberIds.map(id => {
                  const user = this.allUsers.find(u => u.id === Number(id) || u.id === id)
                  return user ? user.name : ''
                }).filter(Boolean)
                item.projectMemberNames = memberNames.join('、')
              }
            })
            
            // 准备导出数据
            const exportData = data.map(item => {
              const row = {}
              this.exportColumns.forEach(col => {
                row[col.label] = item[col.prop] || ''
              })
              return row
            })
            
            // 创建工作簿
            const wb = XLSX.utils.book_new()
            const ws = XLSX.utils.json_to_sheet(exportData)
            
            // 设置列宽
            const colWidths = this.exportColumns.map(() => ({ wch: 20 }))
            ws['!cols'] = colWidths
            
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, '我的申报列表')
            
            // 导出文件
            XLSX.writeFile(wb, '我的申报列表.xlsx')
            
            this.loading = false
            this.$message({
              type: 'success',
              message: '导出成功'
            })
          }).catch(() => {
            this.loading = false
            this.$message.error('导出失败')
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        })
      })
    }
  }
}
</script>

<style scoped></style>
